package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.SHOP_TYPE_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<ShopType> selectByList() {
        String shopTypeJson = stringRedisTemplate.opsForValue().get(SHOP_TYPE_KEY);
        if (StrUtil.isBlank(shopTypeJson)) {
            RLock shopTypeLock = redissonClient.getLock("shopType");
            shopTypeLock.lock(30L, TimeUnit.SECONDS);
            List<ShopType> shopTypeList = this.list();
            shopTypeJson = JSONUtil.toJsonStr(shopTypeList);
            stringRedisTemplate.opsForValue().set(SHOP_TYPE_KEY, shopTypeJson, SHOP_TYPE_TTL,TimeUnit.HOURS);
            shopTypeLock.unlock();
            return shopTypeList;
        }
        return JSONUtil.toList(shopTypeJson, ShopType.class);
    }
}
